home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1998 November: Tool Chest / Dev.CD Nov 98 TC.toast / Sample Code / Snippets / QuickDraw / TE Over Background / TESample.c next >
Encoding:
C/C++ Source or Header  |  1995-02-07  |  59.3 KB  |  1,851 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple TextEdit Sample Application
  6. #
  7. #    TESample
  8. #
  9. #    This file: TESample.c    -    C Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #
  20. #    Components:
  21. #                TESample.p            June 1, 1989
  22. #                TESample.c            June 1, 1989
  23. #                TESampleGlue.a        June 1, 1989    -MPW only-
  24. #                TESample.r            June 1, 1989
  25. #                TESample.h            June 1, 1989
  26. #                PTESample.make        June 1, 1989    -MPW only-
  27. #                CTESample.make        June 1, 1989    -MPW only-
  28. #                TESampleGlue.s        June 1, 1989    -A/UX only-
  29. #                TESampleAUX.r        June 1, 1989    -A/UX only-
  30. #                Makefile            June 1, 1989    -A/UX only-
  31. #
  32. #    TESample is an example application that demonstrates how 
  33. #    to initialize the commonly used toolbox managers, operate 
  34. #    successfully under MultiFinder, handle desk accessories and 
  35. #    create, grow, and zoom windows. The fundamental TextEdit 
  36. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  37. #    also shows how to create and maintain scrollbar controls.
  38. #
  39. #    It does not by any means demonstrate all the techniques you 
  40. #    need for a large application. In particular, Sample does not 
  41. #    cover exception handling, multiple windows/documents, 
  42. #    sophisticated memory management, printing, or undo. All of 
  43. #    these are vital parts of a normal full-sized application.
  44. #
  45. #    This application is an example of the form of a Macintosh 
  46. #    application; it is NOT a template. It is NOT intended to be 
  47. #    used as a foundation for the next world-class, best-selling, 
  48. #    600K application. A stick figure drawing of the human body may 
  49. #    be a good example of the form for a painting, but that does not 
  50. #    mean it should be used as the basis for the next Mona Lisa.
  51. #
  52. #    We recommend that you review this program or Sample before 
  53. #    beginning a new application. Sample is a simple app. which doesn’t 
  54. #    use TextEdit or the Control Manager.
  55. #
  56. ------------------------------------------------------------------------------*/
  57.  
  58.  
  59. /* Segmentation strategy:
  60.  
  61.    This program consists of three segments. Main contains most of the code,
  62.    including the MPW libraries, and the main program. Initialize contains
  63.    code that is only used once, during startup, and can be unloaded after the
  64.    program starts. %A5Init is automatically created by the Linker to initialize
  65.    globals for the MPW libraries and is unloaded right away. */
  66.  
  67.  
  68. /* SetPort strategy:
  69.  
  70.    Toolbox routines do not change the current port. In spite of this, in this
  71.    program we use a strategy of calling SetPort whenever we want to draw or
  72.    make calls which depend on the current port. This makes us less vulnerable
  73.    to bugs in other software which might alter the current port (such as the
  74.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  75.    Hopefully, this also makes the routines from this program more self-contained,
  76.    since they don't depend on the current port setting. */
  77.  
  78.  
  79. /* Clipboard strategy:
  80.  
  81.    This program does not maintain a private scrap. Whenever a cut, copy, or paste
  82.    occurs, we import/export from the public scrap to TextEdit's scrap right away,
  83.    using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  84.    the import/export would be in the activate/deactivate event and suspend/resume
  85.    event routines. */
  86.  
  87. #include <Types.h>
  88. #include <QuickDraw.h>
  89. #include <QDOffscreen.h>
  90. #include <Fonts.h>
  91. #include <Events.h>
  92. #include <Controls.h>
  93. #include <Windows.h>
  94. #include <Menus.h>
  95. #include <TextEdit.h>
  96. #include <Dialogs.h>
  97. #include <Desk.h>
  98. #include <Scrap.h>
  99. #include <ToolUtils.h>
  100. #include <Memory.h>
  101. #include <SegLoad.h>
  102. #include <Files.h>
  103. #include <OSUtils.h>
  104. #include <OSEvents.h>
  105. #include <Packages.h>
  106. #include <Traps.h>
  107. #include <Printing.h>
  108. #include <DiskInit.h>
  109. #include <Errors.h>
  110. #include <GestaltEqu.h>
  111. #include <AppleEvents.h>
  112.  
  113. #include "TESample.h"        /* bring in all the #defines for TESample */
  114.  
  115.  
  116. /* A DocumentRecord contains the WindowRecord for one of our document windows,
  117.    as well as the TEHandle for the text we are editing. Other document fields
  118.    can be added to this record as needed. For a similar example, see how the
  119.    Window Manager and Dialog Manager add fields after the GrafPort. */
  120. typedef struct {
  121.     WindowRecord    docWindow;
  122.     TEHandle        docTE;
  123.     ControlHandle    docVScroll;
  124.     ControlHandle    docHScroll;
  125.     TEClickLoopUPP    docClick;
  126.     GWorldPtr       docImage;
  127. } DocumentRecord, *DocumentPeek;
  128.  
  129.  
  130.  
  131. /* The "g" prefix is used to emphasize that a variable is global. */
  132.  
  133. /* GMac is used to hold the result of a SysEnvirons call. This makes
  134.    it convenient for any routine to check the environment. It is
  135.    global information, anyway. */
  136. SysEnvRec    gMac;                /* set up by Initialize */
  137.  
  138. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  139.    trap is available. If it is false, we know that we must call GetNextEvent. */
  140. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  141.  
  142. /* GInBackground is maintained by our OSEvent handling routines. Any part of
  143.    the program can check it to find out if it is currently in the background. */
  144. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  145.  
  146. /* GNumDocuments is used to keep track of how many open documents there are
  147.    at any time. It is maintained by the routines that open and close documents. */
  148. short        gNumDocuments;        /* maintained by Initialize, DoNew, and DoCloseWindow */
  149.  
  150. #if powerc
  151. TEClickLoopUPP gClickLoopUPP;
  152. #endif
  153.  
  154. ControlActionUPP gHActionUPP;
  155. ControlActionUPP gVActionUPP;
  156.  
  157. QDRectUPP        gQDRectUPP;
  158. QDRgnUPP         gQDRgnUPP;
  159.  
  160.  
  161. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  162.    actual prototypes for parameter type checking. A/UX C does not grok
  163.    prototypes, so eliminate them under A/UX */
  164.     void AlertUser( short error );
  165.     void EventLoop( void );
  166.     void DoEvent( EventRecord *event );
  167.     void AdjustCursor( Point mouse, RgnHandle region );
  168.     void GetGlobalMouse( Point *mouse );
  169.     void DoGrowWindow( WindowPtr window, EventRecord *event );
  170.     void DoZoomWindow( WindowPtr window, short part );
  171.     void ResizeWindow( WindowPtr window );
  172.     void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn );
  173.     void DoUpdate( WindowPtr window );
  174.     void PaintImage( void );
  175.     void DoDeactivate( WindowPtr window );
  176.     void DoActivate( WindowPtr window, Boolean becomingActive );
  177.     void DoContentClick( WindowPtr window, EventRecord *event );
  178.     void DoKeyDown( EventRecord *event );
  179.     unsigned long GetSleep( void );
  180.     void CommonAction( ControlHandle control, short *amount );
  181.     pascal void VActionProc( ControlHandle control, short part );
  182.     pascal void HActionProc( ControlHandle control, short part );
  183.     void DoIdle( void );
  184.     void DrawWindow( WindowPtr window );
  185.     void AdjustMenus( void );
  186.     void DoMenuCommand( long menuResult );
  187.  
  188. pascal void CustomRect(
  189.     GrafVerb verb,
  190.     Rect     *destRect);
  191.  
  192. pascal void CustomRgn(
  193.     GrafVerb  verb,
  194.     RgnHandle destRgn);
  195.  
  196.     void DoNew( void );
  197.     Boolean DoCloseWindow( WindowPtr window );
  198.     void Terminate( void );
  199.     void Initialize( void );
  200.     void BigBadError( short error );
  201.     void GetTERect( WindowPtr window, Rect *teRect );
  202.     void AdjustViewRect( TEHandle docTE );
  203.     void AdjustTE( WindowPtr window );
  204.     void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE,
  205.                     Boolean canRedraw );
  206.     void AdjustScrollValues( WindowPtr window, Boolean canRedraw );
  207.     void AdjustScrollSizes( WindowPtr window );
  208.     void AdjustScrollbars( WindowPtr window, Boolean needsResize );
  209.     #if powerc
  210.     pascal Boolean ClickLoopProc(TEPtr pTE);
  211.     #else
  212.     extern pascal void AsmClickLoopProc(void);
  213.     #endif
  214.     pascal void ClickLoopAddOn(void);
  215.     pascal TEClickLoopUPP GetOldClickLoop(void);
  216.     Boolean IsAppWindow( WindowPtr window );
  217.     Boolean IsDAWindow( WindowPtr window );
  218.     Boolean TrapAvailable( short tNumber);
  219.  
  220.  
  221. /* Define HiWrd and LoWrd macros for efficiency. */
  222. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  223. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  224.  
  225. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  226.    dependency on the ordering of fields within a Rect */
  227. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  228. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  229.  
  230.  
  231. /* This routine is part of the MPW runtime library. This external
  232.    reference to it is done so that we can unload its segment, %A5Init. */
  233.  
  234. #ifndef THINK_C
  235.   extern void _DataInit();
  236. #endif
  237.  
  238.  
  239. /* A reference to our assembly language routine that gets attached to the clikLoop
  240. field of our TE record. */
  241.  
  242. extern pascal void AsmClikLoop();
  243.  
  244. #ifdef powerc
  245.    QDGlobals    qd;
  246. #endif
  247.  
  248. #pragma segment Main
  249. main()
  250. {
  251. #ifndef THINK_C
  252.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  253. #endif
  254.     
  255.     /* 1.01 - call to ForceEnvirons removed */
  256.     
  257.     /*    If you have stack requirements that differ from the default,
  258.         then you could use SetApplLimit to increase StackSpace at 
  259.         this point, before calling MaxApplZone. */
  260.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  261.  
  262.     Initialize();                    /* initialize the program */
  263. #ifndef THINK_C
  264.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  265. #endif
  266.  
  267.     EventLoop();                    /* call the main event loop */
  268. }
  269.  
  270.  
  271. /* Get events forever, and handle them by calling DoEvent.
  272.    Also call AdjustCursor each time through the loop. */
  273.  
  274. #pragma segment Main
  275. void EventLoop()
  276. {
  277.     RgnHandle    cursorRgn;
  278.     Boolean        gotEvent;
  279.     EventRecord    event;
  280.     Point        mouse;
  281.  
  282.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  283.     do {
  284.         /* use WNE if it is available */
  285.         if ( gHasWaitNextEvent ) {
  286.             GetGlobalMouse(&mouse);
  287.             AdjustCursor(mouse, cursorRgn);
  288.             gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
  289.         }
  290.         else {
  291.             SystemTask();
  292.             gotEvent = GetNextEvent(everyEvent, &event);
  293.         }
  294.         if ( gotEvent ) {
  295.             /* make sure we have the right cursor before handling the event */
  296.             AdjustCursor(event.where, cursorRgn);
  297.             DoEvent(&event);
  298.         }
  299.         else
  300.             DoIdle();                /* perform idle tasks when it’s not our event */
  301.         /*    If you are using modeless dialogs that have editText items,
  302.             you will want to call IsDialogEvent to give the caret a chance
  303.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  304.             for a non-NIL value before calling IsDialogEvent. */
  305.     } while ( true );    /* loop forever; we quit via ExitToShell */
  306. } /*EventLoop*/
  307.  
  308.  
  309. /* Do the right thing for an event. Determine what kind of event it is, and call
  310.  the appropriate routines. */
  311.  
  312. #pragma segment Main
  313. void DoEvent(event)
  314.     EventRecord    *event;
  315. {
  316.     short        part, err;
  317.     WindowPtr    window;
  318.     char        key;
  319.     Point        aPoint;
  320.  
  321.     switch ( event->what ) {
  322.         case nullEvent:
  323.             /* we idle for null/mouse moved events ands for events which aren’t
  324.                 ours (see EventLoop) */
  325.             DoIdle();
  326.             break;
  327.         case mouseDown:
  328.             part = FindWindow(event->where, &window);
  329.             switch ( part ) {
  330.                 case inMenuBar:             /* process a mouse menu command (if any) */
  331.                     AdjustMenus();    /* bring ’em up-to-date */
  332.                     DoMenuCommand(MenuSelect(event->where));
  333.                     break;
  334.                 case inSysWindow:           /* let the system handle the mouseDown */
  335.                     SystemClick(event, window);
  336.                     break;
  337.                 case inContent:
  338.                     if ( window != FrontWindow() ) {
  339.                         SelectWindow(window);
  340.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  341.                     } else
  342.                         DoContentClick(window, event);
  343.                     break;
  344.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  345.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  346.                     break;
  347.                 case inGoAway:
  348.                     if ( TrackGoAway(window, event->where) )
  349.                         DoCloseWindow(window); /* we don’t care if the user cancelled */
  350.                     break;
  351.                 case inGrow:
  352.                     DoGrowWindow(window, event);
  353.                     break;
  354.                 case inZoomIn:
  355.                 case inZoomOut:
  356.                 if ( TrackBox(window, event->where, part) )
  357.                         DoZoomWindow(window, part);
  358.                     break;
  359.             }
  360.             break;
  361.         case keyDown:
  362.         case autoKey:                       /* check for menukey equivalents */
  363.             key = event->message & charCodeMask;
  364.             if ( event->modifiers & cmdKey ) {    /* Command key down */
  365.                 if ( event->what == keyDown ) {
  366.                     AdjustMenus();            /* enable/disable/check menu items properly */
  367.                     DoMenuCommand(MenuKey(key));
  368.                 }
  369.             } else
  370.                 DoKeyDown(event);
  371.             break;
  372.         case activateEvt:
  373.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  374.             break;
  375.         case updateEvt:
  376.             DoUpdate((WindowPtr) event->message);
  377.             break;
  378.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  379.             to a diskEvt, so that the user can format a floppy. */
  380.         case diskEvt:
  381.             if ( HiWord(event->message) != noErr ) {
  382.                 SetPt(&aPoint, kDILeft, kDITop);
  383.                 err = DIBadMount(aPoint, event->message);
  384.             }
  385.             break;
  386.         case kOSEvent:
  387.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  388.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  389.                 case kMouseMovedMessage:
  390.                     DoIdle();                    /* mouse-moved is also an idle event */
  391.                     break;
  392.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  393.                     gInBackground = (event->message & kResumeMask) == 0;
  394.                     DoActivate(FrontWindow(), !gInBackground);
  395.                     break;
  396.             }
  397.             break;
  398.     }
  399. } /*DoEvent*/
  400.  
  401.  
  402. /*    Change the cursor's shape, depending on its position. This also calculates the region
  403.     where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
  404.     this region, an event is generated. If there is more to the event than just
  405.     “the mouse moved”, we get called before the event is processed to make sure
  406.     the cursor is the right one. In any (ahem) event, this is called again before we
  407.     fall back into WNE. */
  408.  
  409. #pragma segment Main
  410. void AdjustCursor(mouse,region)
  411.     Point        mouse;
  412.     RgnHandle    region;
  413. {
  414.     WindowPtr    window;
  415.     RgnHandle    arrowRgn;
  416.     RgnHandle    iBeamRgn;
  417.     Rect        iBeamRect;
  418.  
  419.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  420.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  421.         /* calculate regions for different cursor shapes */
  422.         arrowRgn = NewRgn();
  423.         iBeamRgn = NewRgn();
  424.  
  425.         /* start arrowRgn wide open */
  426.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  427.  
  428.         /* calculate iBeamRgn */
  429.         if ( IsAppWindow(window) ) {
  430.             iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
  431.             SetPort(window);    /* make a global version of the viewRect */
  432.             LocalToGlobal(&TopLeft(iBeamRect));
  433.             LocalToGlobal(&BotRight(iBeamRect));
  434.             RectRgn(iBeamRgn, &iBeamRect);
  435.             /* we temporarily change the port’s origin to “globalfy” the visRgn */
  436.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  437.             SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
  438.             SetOrigin(0, 0);
  439.         }
  440.  
  441.         /* subtract other regions from arrowRgn */
  442.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  443.  
  444.         /* change the cursor and the region parameter */
  445.         if ( PtInRgn(mouse, iBeamRgn) ) {
  446.             SetCursor(*GetCursor(iBeamCursor));
  447.             CopyRgn(iBeamRgn, region);
  448.         } else {
  449.             SetCursor(&qd.arrow);
  450.             CopyRgn(arrowRgn, region);
  451.         }
  452.  
  453.         DisposeRgn(arrowRgn);
  454.         DisposeRgn(iBeamRgn);
  455.     }
  456. } /*AdjustCursor*/
  457.  
  458.  
  459. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  460.     it will return either a pending event or a null event. In either case,
  461.     the where field of the event record will contain the current position
  462.     of the mouse in global coordinates and the modifiers field will reflect
  463.     the current state of the modifiers. Another way to get the global
  464.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  465.     being sure that thePort is set to a valid port. */
  466.  
  467. #pragma segment Main
  468. void GetGlobalMouse(mouse)
  469.     Point    *mouse;
  470. {
  471.     EventRecord    event;
  472.     
  473.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  474.     *mouse = event.where;                /* just the mouse position */
  475. } /*GetGlobalMouse*/
  476.  
  477.  
  478. /*    Called when a mouseDown occurs in the grow box of an active window. In
  479.     order to eliminate any 'flicker', we want to invalidate only what is
  480.     necessary. Since ResizeWindow invalidates the whole portRect, we save
  481.     the old TE viewRect, intersect it with the new TE viewRect, and
  482.     remove the result from the update region. However, we must make sure
  483.     that any old update region that might have been around gets put back. */
  484.  
  485. #pragma segment Main
  486. void DoGrowWindow(window,event)
  487.     WindowPtr    window;
  488.     EventRecord    *event;
  489. {
  490.     long        growResult;
  491.     Rect        tempRect;
  492.     RgnHandle    tempRgn;
  493.     DocumentPeek doc;
  494.     
  495.     tempRect = qd.screenBits.bounds;                    /* set up limiting values */
  496.     tempRect.left = kMinDocDim;
  497.     tempRect.top = kMinDocDim;
  498.     growResult = GrowWindow(window, event->where, &tempRect);
  499.     /* see if it really changed size */
  500.     if ( growResult != 0 ) {
  501.         doc = (DocumentPeek) window;
  502.         tempRect = (*doc->docTE)->viewRect;                /* save old text box */
  503.         tempRgn = NewRgn();
  504.         GetLocalUpdateRgn(window, tempRgn);                /* get localized update region */
  505.         SizeWindow(window, LoWrd(growResult), HiWrd(growResult), true);
  506.         ResizeWindow(window);
  507.         /* calculate & validate the region that hasn’t changed so it won’t get redrawn */
  508.         SectRect(&tempRect, &(*doc->docTE)->viewRect, &tempRect);
  509.         ValidRect(&tempRect);                            /* take it out of update */
  510.         InvalRgn(tempRgn);                                /* put back any prior update */
  511.         DisposeRgn(tempRgn);
  512.     }
  513. } /* DoGrowWindow */
  514.  
  515.  
  516. /*     Called when a mouseClick occurs in the zoom box of an active window.
  517.     Everything has to get re-drawn here, so we don't mind that
  518.     ResizeWindow invalidates the whole portRect. */
  519.  
  520. #pragma segment Main
  521. void DoZoomWindow(window,part)
  522.     WindowPtr    window;
  523.     short        part;
  524. {
  525.     EraseRect(&window->portRect);
  526.     ZoomWindow(window, part, window == FrontWindow());
  527.     ResizeWindow(window);
  528. } /*  DoZoomWindow */
  529.  
  530.  
  531. /* Called when the window has been resized to fix up the controls and content. */
  532. #pragma segment Main
  533. void ResizeWindow(window)
  534.     WindowPtr    window;
  535. {
  536.     CGrafPtr savedPort;   /* Saves the current port for later restoring */
  537.     GDHandle savedDevice; /* Saves the current GDevice for later restoring */
  538.  
  539.     AdjustScrollbars(window, true);
  540.     AdjustTE(window);
  541.     InvalRect(&window->portRect);
  542.  
  543.     /* Resize the background image to the new size of the window */
  544.     GetGWorld( /*<*/&savedPort, /*<*/&savedDevice );
  545.     UpdateGWorld( &((DocumentPeek)window)->docImage, 0, &window->portRect, nil, nil, 0 );
  546.     SetGWorld( ((DocumentPeek)window)->docImage, nil );
  547.     PaintImage();
  548.     SetGWorld( savedPort, savedDevice );
  549. } /* ResizeWindow */
  550.  
  551.  
  552. /* Returns the update region in local coordinates */
  553. #pragma segment Main
  554. void GetLocalUpdateRgn(window,localRgn)
  555.     WindowPtr    window;
  556.     RgnHandle    localRgn;
  557. {
  558.     CopyRgn(((WindowPeek) window)->updateRgn, localRgn);    /* save old update region */
  559.     OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
  560. } /* GetLocalUpdateRgn */
  561.  
  562.  
  563. /*    This is called when an update event is received for a window.
  564.     It calls DrawWindow to draw the contents of an application window.
  565.     As an efficiency measure that does not have to be followed, it
  566.     calls the drawing routine only if the visRgn is non-empty. This
  567.     will handle situations where calculations for drawing or drawing
  568.     itself is very time-consuming. */
  569.  
  570. #pragma segment Main
  571. void DoUpdate(window)
  572.     WindowPtr    window;
  573. {
  574.     if ( IsAppWindow(window) ) {
  575.         BeginUpdate(window);                /* this sets up the visRgn */
  576.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  577.             DrawWindow(window);
  578.         EndUpdate(window);
  579.     }
  580. } /*DoUpdate*/
  581.  
  582.  
  583. static void PaintImage()
  584. {
  585.     CGrafPtr  savedPort;    /* Pointer to saved CGrafPort for later restoring */
  586.     GDHandle  savedGDevice; /* Handle to saved GDevice for later restoring */
  587.     RGBColor  rampColor;    /* Color to use when drawing a step of the ramp */
  588.     short     maxRampCount; /* Number of pixels in a ramp */
  589.     short     rampWidth;    /* Width of each ramp in pixels */
  590.     short     rampFactor;   /* Value to set a color component to in a ramp */
  591.     short     pinFactor;    /* Value to pin a color component to in a ramp */
  592.     short     x;            /* Horizontal coordinate to draw ramp step */
  593.     short     y;            /* Vertical coordinate to draw ramp step */
  594.  
  595.     GetGWorld( /*<*/&savedPort, /*<*/&savedGDevice );
  596.  
  597.     /* Pin component values at $0000 first, then at $FFFF */
  598.     maxRampCount = savedPort->portRect.bottom - savedPort->portRect.top;
  599.     rampWidth = (savedPort->portRect.right - savedPort->portRect.left) / 16;
  600.     for (pinFactor = 0; pinFactor >= -1; pinFactor--)
  601.     {
  602.         /* Loop on y coordinate over entire GrafPort */
  603.         for (y = 0; y < maxRampCount; y++)
  604.         {
  605.             /* Calculate value of components that are dynamic in a ramp */
  606.             rampFactor = y * 65535 / maxRampCount;
  607.             if (pinFactor == -1)
  608.             {
  609.                 /* If pinning at $FFFF, then use one’s comp of rampFactor */
  610.                 rampFactor ^= 0xFFFF;
  611.                 x = rampWidth;
  612.             }
  613.             else
  614.                 x = 0;
  615.  
  616.             rampColor.red = rampFactor;
  617.             rampColor.green = rampFactor;
  618.             rampColor.blue = rampFactor;
  619.             RGBForeColor( &rampColor );
  620.             MoveTo( x, y );
  621.             Line( rampWidth, 0 );
  622.  
  623.             x += rampWidth * 2;
  624.             rampColor.blue = pinFactor;
  625.             RGBForeColor( &rampColor );
  626.             MoveTo( x, y );
  627.             Line( rampWidth, 0 );
  628.  
  629.             x += rampWidth * 2;
  630.             rampColor.green = pinFactor;
  631.             RGBForeColor( &rampColor );
  632.             MoveTo( x, y );
  633.             Line( rampWidth, 0 );
  634.  
  635.             x += rampWidth * 2;
  636.             rampColor.blue = rampFactor;
  637.             RGBForeColor( &rampColor );
  638.             MoveTo( x, y );
  639.             Line( rampWidth, 0 );
  640.  
  641.             x += rampWidth * 2;
  642.             rampColor.red = pinFactor;
  643.             RGBForeColor( &rampColor );
  644.             MoveTo( x, y );
  645.             Line( rampWidth, 0 );
  646.  
  647.             x += rampWidth * 2;
  648.             rampColor.green = rampFactor;
  649.             RGBForeColor( &rampColor );
  650.             MoveTo( x, y );
  651.             Line( rampWidth, 0 );
  652.  
  653.             x += rampWidth * 2;
  654.             rampColor.blue = pinFactor;
  655.             RGBForeColor( &rampColor );
  656.             MoveTo( x, y );
  657.             Line( rampWidth, 0 );
  658.  
  659.             x += rampWidth * 2;
  660.             rampColor.green = pinFactor;
  661.             RGBForeColor( &rampColor );
  662.             MoveTo( x, y );
  663.             Line( rampWidth, 0 );
  664.         }
  665.     }
  666. }
  667.  
  668.  
  669. /*    This is called when a window is activated or deactivated.
  670.     It calls TextEdit to deal with the selection. */
  671.  
  672. #pragma segment Main
  673. void DoActivate(window, becomingActive)
  674.     WindowPtr    window;
  675.     Boolean        becomingActive;
  676. {
  677.     RgnHandle    tempRgn, clipRgn;
  678.     Rect        growRect;
  679.     DocumentPeek doc;
  680.     
  681.     if ( IsAppWindow(window) ) {
  682.         doc = (DocumentPeek) window;
  683.         if ( becomingActive ) {
  684.             /*    since we don’t want TEActivate to draw a selection in an area where
  685.                 we’re going to erase and redraw, we’ll clip out the update region
  686.                 before calling it. */
  687.             tempRgn = NewRgn();
  688.             clipRgn = NewRgn();
  689.             GetLocalUpdateRgn(window, tempRgn);            /* get localized update region */
  690.             GetClip(clipRgn);
  691.             DiffRgn(clipRgn, tempRgn, tempRgn);            /* subtract updateRgn from clipRgn */
  692.             SetClip(tempRgn);
  693.             TEActivate(doc->docTE);
  694.             SetClip(clipRgn);                            /* restore the full-blown clipRgn */
  695.             DisposeRgn(tempRgn);
  696.             DisposeRgn(clipRgn);
  697.             
  698.             /* the controls must be redrawn on activation: */
  699.             (*doc->docVScroll)->contrlVis = kControlVisible;
  700.             (*doc->docHScroll)->contrlVis = kControlVisible;
  701.             InvalRect(&(*doc->docVScroll)->contrlRect);
  702.             InvalRect(&(*doc->docHScroll)->contrlRect);
  703.             /* the growbox needs to be redrawn on activation: */
  704.             growRect = window->portRect;
  705.             /* adjust for the scrollbars */
  706.             growRect.top = growRect.bottom - kScrollbarAdjust;
  707.             growRect.left = growRect.right - kScrollbarAdjust;
  708.             InvalRect(&growRect);
  709.         }
  710.         else {        
  711.             TEDeactivate(doc->docTE);
  712.             /* the controls must be hidden on deactivation: */
  713.             HideControl(doc->docVScroll);
  714.             HideControl(doc->docHScroll);
  715.             /* the growbox should be changed immediately on deactivation: */
  716.             DrawGrowIcon(window);
  717.         }
  718.     }
  719. } /*DoActivate*/
  720.  
  721.  
  722. /*    This is called when a mouseDown occurs in the content of a window. */
  723.  
  724. #pragma segment Main
  725. void DoContentClick(window,event)
  726.     WindowPtr    window;
  727.     EventRecord    *event;
  728. {
  729.     Point        mouse;
  730.     ControlHandle control;
  731.     short        part, value;
  732.     Boolean        shiftDown;
  733.     DocumentPeek doc;
  734.     Rect        teRect;
  735.  
  736.     if ( IsAppWindow(window) ) {
  737.         SetPort(window);
  738.         mouse = event->where;                            /* get the click position */
  739.         GlobalToLocal(&mouse);
  740.         doc = (DocumentPeek) window;
  741.         /* see if we are in the viewRect. if so, we won’t check the controls */
  742.         GetTERect(window, &teRect);
  743.         if ( PtInRect(mouse, &teRect) ) {
  744.             /* see if we need to extend the selection */
  745.             shiftDown = (event->modifiers & shiftKey) != 0;    /* extend if Shift is down */
  746.             TEClick(mouse, shiftDown, doc->docTE);
  747.         } else {
  748.             part = FindControl(mouse, window, &control);
  749.             switch ( part ) {
  750.                 case 0:                            /* do nothing for viewRect case */
  751.                     break;
  752.                 case inThumb:
  753.                     value = GetCtlValue(control);
  754.                     part = TrackControl(control, mouse, nil);
  755.                     if ( part != 0 ) {
  756.                         value -= GetCtlValue(control);
  757.                         /* value now has CHANGE in value; if value changed, scroll */
  758.                         if ( value != 0 )
  759.                             if ( control == doc->docVScroll )
  760.                                 TEScroll(0, value * (*doc->docTE)->lineHeight, doc->docTE);
  761.                             else
  762.                                 TEScroll(value, 0, doc->docTE);
  763.                     }
  764.                     break;
  765.                 default:                        /* they clicked in an arrow, so track & scroll */
  766.                     if ( control == doc->docVScroll )
  767.                         value = TrackControl(control, mouse, gVActionUPP);
  768.                     else
  769.                         value = TrackControl(control, mouse, gHActionUPP);
  770.                     break;
  771.             }
  772.         }
  773.     }
  774. } /*DoContentClick*/
  775.  
  776.  
  777. /* This is called for any keyDown or autoKey events, except when the
  778.  Command key is held down. It looks at the frontmost window to decide what
  779.  to do with the key typed. */
  780.  
  781. #pragma segment Main
  782. void DoKeyDown(event)
  783.     EventRecord    *event;
  784. {
  785.     WindowPtr    window;
  786.     char        key;
  787.     TEHandle    te;
  788.  
  789.     window = FrontWindow();
  790.     if ( IsAppWindow(window) ) {
  791.         te = ((DocumentPeek) window)->docTE;
  792.         key = event->message & charCodeMask;
  793.         /* we have a char. for our window; see if we are still below TextEdit’s
  794.             limit for the number of characters (but deletes are always rad) */
  795.         if ( key == kDelChar ||
  796.                 (*te)->teLength - ((*te)->selEnd - (*te)->selStart) + 1 <
  797.                 kMaxTELength ) {
  798.             TEKey(key, te);
  799.             AdjustScrollbars(window, false);
  800.             AdjustTE(window);
  801.         } else
  802.             AlertUser(eExceedChar);
  803.     }
  804. } /*DoKeyDown*/
  805.  
  806.  
  807. /*    Calculate a sleep value for WaitNextEvent. This takes into account the things
  808.     that DoIdle does with idle time. */
  809.  
  810. #pragma segment Main
  811. unsigned long GetSleep()
  812. {
  813.     long        sleep;
  814.     WindowPtr    window;
  815.     TEHandle    te;
  816.  
  817.     sleep = 60;                        /* default value for sleep */
  818.     if ( !gInBackground ) {
  819.         window = FrontWindow();            /* and the front window is ours... */
  820.         if ( IsAppWindow(window) ) {
  821.             te = ((DocumentPeek) (window))->docTE;    /* and the selection is an insertion point... */
  822.             if ( (*te)->selStart == (*te)->selEnd )
  823.                 sleep = GetCaretTime();        /* blink time for the insertion point */
  824.         }
  825.     }
  826.     return sleep;
  827. } /*GetSleep*/
  828.  
  829.  
  830. /*    Common algorithm for pinning the value of a control. It returns the actual amount
  831.     the value of the control changed. Note the pinning is done for the sake of returning
  832.     the amount the control value changed. */
  833.  
  834. #pragma segment Main
  835. void CommonAction(control,amount)
  836.     ControlHandle control;
  837.     short        *amount;
  838. {
  839.     short        value, max;
  840.     
  841.     value = GetCtlValue(control);    /* get current value */
  842.     max = GetCtlMax(control);        /* and maximum value */
  843.     *amount = value - *amount;
  844.     if ( *amount < 0 )
  845.         *amount = 0;
  846.     else if ( *amount > max )
  847.         *amount = max;
  848.     SetCtlValue(control, *amount);
  849.     *amount = value - *amount;        /* calculate the real change */
  850. } /* CommonAction */
  851.  
  852.  
  853. /* Determines how much to change the value of the vertical scrollbar by and how
  854.     much to scroll the TE record. */
  855.  
  856. #pragma segment Main
  857. pascal void VActionProc(control,part)
  858.     ControlHandle control;
  859.     short        part;
  860. {
  861.     short        amount;
  862.     WindowPtr    window;
  863.     TEPtr        te;
  864.     
  865.     if ( part != 0 ) {                /* if it was actually in the control */
  866.         window = (*control)->contrlOwner;
  867.         te = *((DocumentPeek) window)->docTE;
  868.         switch ( part ) {
  869.             case inUpButton:
  870.             case inDownButton:        /* one line */
  871.                 amount = 1;
  872.                 break;
  873.             case inPageUp:            /* one page */
  874.             case inPageDown:
  875.                 amount = (te->viewRect.bottom - te->viewRect.top) / te->lineHeight;
  876.                 break;
  877.         }
  878.         if ( (part == inDownButton) || (part == inPageDown) )
  879.             amount = -amount;        /* reverse direction for a downer */
  880.         CommonAction(control, &amount);
  881.         if ( amount != 0 )
  882.             TEScroll(0, amount * te->lineHeight, ((DocumentPeek) window)->docTE);
  883.     }
  884. } /* VActionProc */
  885.  
  886.  
  887. /* Determines how much to change the value of the horizontal scrollbar by and how
  888. much to scroll the TE record. */
  889.  
  890. #pragma segment Main
  891. pascal void HActionProc(control,part)
  892.     ControlHandle control;
  893.     short        part;
  894. {
  895.     short        amount;
  896.     WindowPtr    window;
  897.     TEPtr        te;
  898.     
  899.     if ( part != 0 ) {
  900.         window = (*control)->contrlOwner;
  901.         te = *((DocumentPeek) window)->docTE;
  902.         switch ( part ) {
  903.             case inUpButton:
  904.             case inDownButton:        /* a few pixels */
  905.                 amount = kButtonScroll;
  906.                 break;
  907.             case inPageUp:            /* a page */
  908.             case inPageDown:
  909.                 amount = te->viewRect.right - te->viewRect.left;
  910.                 break;
  911.         }
  912.         if ( (part == inDownButton) || (part == inPageDown) )
  913.             amount = -amount;        /* reverse direction */
  914.         CommonAction(control, &amount);
  915.         if ( amount != 0 )
  916.             TEScroll(amount, 0, ((DocumentPeek) window)->docTE);
  917.     }
  918. } /* VActionProc */
  919.  
  920.  
  921. /* This is called whenever we get a null event et al.
  922.  It takes care of necessary periodic actions. For this program, it calls TEIdle. */
  923.  
  924. #pragma segment Main
  925. void DoIdle()
  926. {
  927.     WindowPtr    window;
  928.  
  929.     window = FrontWindow();
  930.     if ( IsAppWindow(window) )
  931.         TEIdle(((DocumentPeek) window)->docTE);
  932. } /*DoIdle*/
  933.  
  934.  
  935. /* Draw the contents of an application window. */
  936.  
  937. #pragma segment Main
  938. void DrawWindow(window)
  939.     WindowPtr    window;
  940. {
  941.     SetPort(window);
  942.     EraseRect( &window->portRect );
  943.     DrawControls(window);
  944.     DrawGrowIcon(window);
  945.     TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
  946. } /*DrawWindow*/
  947.  
  948.  
  949. /*    Enable and disable menus based on the current state.
  950.     The user can only select enabled menu items. We set up all the menu items
  951.     before calling MenuSelect or MenuKey, since these are the only times that
  952.     a menu item can be selected. Note that MenuSelect is also the only time
  953.     the user will see menu items. This approach to deciding what enable/
  954.     disable state a menu item has the advantage of concentrating all
  955.     the decision-making in one routine, as opposed to being spread throughout
  956.     the application. Other application designs may take a different approach
  957.     that may or may not be as valid. */
  958.  
  959. #pragma segment Main
  960. void AdjustMenus()
  961. {
  962.     WindowPtr    window;
  963.     MenuHandle    menu;
  964.     long        offset;
  965.     Boolean        undo;
  966.     Boolean        cutCopyClear;
  967.     Boolean        paste;
  968.     TEHandle    te;
  969.  
  970.     window = FrontWindow();
  971.  
  972.     menu = GetMHandle(mFile);
  973.     if ( gNumDocuments < kMaxOpenDocuments )
  974.         EnableItem(menu, iNew);        /* New is enabled when we can open more documents */
  975.     else
  976.         DisableItem(menu, iNew);
  977.     if ( window != nil )            /* Close is enabled when there is a window to close */
  978.         EnableItem(menu, iClose);
  979.     else
  980.         DisableItem(menu, iClose);
  981.  
  982.     menu = GetMHandle(mEdit);
  983.     undo = false;
  984.     cutCopyClear = false;
  985.     paste = false;
  986.     if ( IsDAWindow(window) ) {
  987.         undo = true;                /* all editing is enabled for DA windows */
  988.         cutCopyClear = true;
  989.         paste = true;
  990.     } else if ( IsAppWindow(window) ) {
  991.         te = ((DocumentPeek) window)->docTE;
  992.         if ( (*te)->selStart < (*te)->selEnd )
  993.             cutCopyClear = true;
  994.             /* Cut, Copy, and Clear is enabled for app. windows with selections */
  995.         if ( GetScrap(nil, 'TEXT', &offset)  > 0)
  996.             paste = true;            /* if there’s any text in the clipboard, paste is enabled */
  997.     }
  998.     if ( undo )
  999.         EnableItem(menu, iUndo);
  1000.     else
  1001.         DisableItem(menu, iUndo);
  1002.     if ( cutCopyClear ) {
  1003.         EnableItem(menu, iCut);
  1004.         EnableItem(menu, iCopy);
  1005.         EnableItem(menu, iClear);
  1006.     } else {
  1007.         DisableItem(menu, iCut);
  1008.         DisableItem(menu, iCopy);
  1009.         DisableItem(menu, iClear);
  1010.     }
  1011.     if ( paste )
  1012.         EnableItem(menu, iPaste);
  1013.     else
  1014.         DisableItem(menu, iPaste);
  1015. } /*AdjustMenus*/
  1016.  
  1017.  
  1018. /*    This is called when an item is chosen from the menu bar (after calling
  1019.     MenuSelect or MenuKey). It does the right thing for each command. */
  1020.  
  1021. #pragma segment Main
  1022. void DoMenuCommand(menuResult)
  1023.     long        menuResult;
  1024. {
  1025.     short        menuID, menuItem;
  1026.     short        itemHit, daRefNum;
  1027.     Str255        daName;
  1028.     OSErr        saveErr;
  1029.     TEHandle    te;
  1030.     WindowPtr    window;
  1031.     Handle        aHandle;
  1032.     long        oldSize, newSize;
  1033.     long        total, contig;
  1034.  
  1035.     window = FrontWindow();
  1036.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  1037.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  1038.     switch ( menuID ) {
  1039.         case mApple:
  1040.             switch ( menuItem ) {
  1041.                 case iAbout:        /* bring up alert for About */
  1042.                     itemHit = Alert(rAboutAlert, nil);
  1043.                     break;
  1044.                 default:            /* all non-About items in this menu are DAs et al */
  1045.                     /* type Str255 is an array in MPW 3 */
  1046.                     GetItem(GetMHandle(mApple), menuItem, daName);
  1047.                     daRefNum = OpenDeskAcc(daName);
  1048.                     break;
  1049.             }
  1050.             break;
  1051.         case mFile:
  1052.             switch ( menuItem ) {
  1053.                 case iNew:
  1054.                     DoNew();
  1055.                     break;
  1056.                 case iClose:
  1057.                     DoCloseWindow(FrontWindow());            /* ignore the result */
  1058.                     break;
  1059.                 case iQuit:
  1060.                     Terminate();
  1061.                     break;
  1062.             }
  1063.             break;
  1064.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  1065.             if ( !SystemEdit(menuItem-1) ) {
  1066.                 te = ((DocumentPeek) FrontWindow())->docTE;
  1067.                 switch ( menuItem ) {
  1068.                     case iCut:
  1069.                         if ( ZeroScrap() == noErr ) {
  1070.                             PurgeSpace(&total, &contig);
  1071.                             if ((*te)->selEnd - (*te)->selStart + kTESlop > contig)
  1072.                                 AlertUser(eNoSpaceCut);
  1073.                             else 
  1074.                                 {
  1075.                                 TECut(te);
  1076.                                 if ( TEToScrap() != noErr ) {
  1077.                                     AlertUser(eNoCut);
  1078.                                     ZeroScrap();
  1079.                                 }
  1080.                             }
  1081.                         }
  1082.                         break;
  1083.                     case iCopy:
  1084.                         if ( ZeroScrap() == noErr ) {
  1085.                             TECopy(te);    /* after copying, export the TE scrap */
  1086.                             if ( TEToScrap() != noErr ) {
  1087.                                 AlertUser(eNoCopy);
  1088.                                 ZeroScrap();
  1089.                             }
  1090.                         }
  1091.                         break;
  1092.                     case iPaste:    /* import the TE scrap before pasting */
  1093.                         if ( TEFromScrap() == noErr ) {
  1094.                             if ( TEGetScrapLen() + ((*te)->teLength -
  1095.                                 ((*te)->selEnd - (*te)->selStart)) > kMaxTELength )
  1096.                                 AlertUser(eExceedPaste);
  1097.                             else {
  1098.                                 aHandle = (Handle) TEGetText(te);
  1099.                                 oldSize = GetHandleSize(aHandle);
  1100.                                 newSize = oldSize + TEGetScrapLen() + kTESlop;
  1101.                                 SetHandleSize(aHandle, newSize);
  1102.                                 saveErr = MemError();
  1103.                                 SetHandleSize(aHandle, oldSize);
  1104.                                 if (saveErr != noErr)
  1105.                                     AlertUser(eNoSpacePaste);
  1106.                                 else
  1107.                                     TEPaste(te);
  1108.                             }
  1109.                         }
  1110.                         else
  1111.                             AlertUser(eNoPaste);
  1112.                         break;
  1113.                     case iClear:
  1114.                         TEDelete(te);
  1115.                         break;
  1116.                 }
  1117.             AdjustScrollbars(window, false);
  1118.             AdjustTE(window);
  1119.             }
  1120.             break;
  1121.     }
  1122.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  1123. } /*DoMenuCommand*/
  1124.  
  1125.  
  1126. pascal void CustomRect(
  1127.     GrafVerb verb,      /* Operation to perform */
  1128.     Rect     *destRect) /* Rectangle to be drawn */
  1129. {
  1130.     GrafPtr   currPort;          /* Port that this bottleneck is attached to */
  1131.     GWorldPtr backImage;         /* The window’s background image */
  1132.     TEHandle  docText;           /* Document’s TextEdit record */
  1133.     RgnHandle clippedDestRgn;    /* Region that covers clippedDestRect area */
  1134.     RgnHandle destRectRgn;       /* Region that covers destRect */
  1135.     Rect      textRect;          /* Copy of the TextEdit record’s viewRect */
  1136.     Rect      clippedDestRect;   /* Rectangle to copy GWorld into */
  1137.     Rect      clippedSourceRect; /* Rectangle to copy GWorld image from */
  1138.     short     horzOffset;        /* Horizontal offset of destRect from viewRect */
  1139.     short     vertOffset;        /* Vertical offset of destRect from viewRect */
  1140.  
  1141.     if (verb == erase)
  1142.     {
  1143.         /* Get the document’s background image and TextEdit record */
  1144.         GetPort( /*<*/&currPort );
  1145.         backImage = ((DocumentPeek)currPort)->docImage;
  1146.         docText = ((DocumentPeek)currPort)->docTE;
  1147.         textRect = (**docText).viewRect;
  1148.  
  1149.         /* Get the amount that the TextEdit record is scrolled */
  1150.         horzOffset = textRect.left - (**docText).destRect.left;
  1151.         vertOffset = textRect.top - (**docText).destRect.top;
  1152.  
  1153.         /* Source rect is dest rect scrolled, clipped to viewRect and off-screen port */
  1154.         clippedSourceRect = *destRect;
  1155.         SectRect( &clippedSourceRect, &textRect, /*<*/&clippedSourceRect );
  1156.         OffsetRect( /*◊*/&clippedSourceRect, horzOffset, vertOffset );
  1157.         SectRect( &clippedSourceRect, &backImage->portRect, /*<*/&clippedSourceRect );
  1158.  
  1159.         /* Dest rect is clipped to viewRect and same size and source rect */
  1160.         clippedDestRect = *destRect;
  1161.         SectRect( &clippedDestRect, &textRect, /*<*/&clippedDestRect );
  1162.         clippedDestRect.right = clippedDestRect.left + (clippedSourceRect.right -
  1163.                 clippedSourceRect.left);
  1164.         clippedDestRect.bottom = clippedDestRect.top + (clippedSourceRect.bottom -
  1165.                 clippedSourceRect.top);
  1166.  
  1167.         /* Draw the background instead of erasing */
  1168.         CopyBits( &((GrafPtr)backImage)->portBits, &currPort->portBits,
  1169.                 &clippedSourceRect, &clippedDestRect,
  1170.                 srcCopy, nil );
  1171.  
  1172.         /* Erase the area outside of the area of the background */
  1173.         clippedDestRgn = NewRgn();
  1174.         destRectRgn = NewRgn();
  1175.         RectRgn( clippedDestRgn, &clippedDestRect );
  1176.         RectRgn( destRectRgn, destRect );
  1177.         DiffRgn( destRectRgn, clippedDestRgn, clippedDestRgn );
  1178.         StdRgn( erase, clippedDestRgn );
  1179.         DisposeRgn( clippedDestRgn );
  1180.         DisposeRgn( destRectRgn );
  1181.     }
  1182.     else if (verb == invert)
  1183.     {
  1184.         /* Turn off colored hilighting so that we can see something */
  1185.         *((char *)0x0938) |= 0x80;
  1186.         StdRect( verb, destRect );
  1187.     }
  1188.     else
  1189.         /* Nothing special; just call original bottleneck */
  1190.         StdRect( verb, destRect );
  1191. }
  1192.  
  1193.  
  1194. pascal void CustomRgn(
  1195.     GrafVerb  verb,    /* Operation to perform */
  1196.     RgnHandle destRgn) /* Region to be drawn */
  1197. {
  1198.     GrafPtr   currPort;          /* Port that this bottleneck is attached to */
  1199.     GWorldPtr backImage;         /* The window’s background image */
  1200.     TEHandle  docText;           /* Document’s TextEdit record */
  1201.     Rect      textRect;          /* Copy of the TextEdit record’s viewRect */
  1202.     Rect      clippedDestRect;   /* Rectangle to copy GWorld into */
  1203.     Rect      clippedSourceRect; /* Rectangle to copy GWorld image from */
  1204.     Rect      destRect;          /* Rectangle that circumscribes destRgn */
  1205.     short     horzOffset;        /* Horizontal offset of destRect from viewRect */
  1206.     short     vertOffset;        /* Vertical offset of destRect from viewRect */
  1207.  
  1208.     if (verb == erase)
  1209.     {
  1210.         /* Get the document’s background image and TextEdit record */
  1211.         GetPort( /*<*/&currPort );
  1212.         backImage = ((DocumentPeek)currPort)->docImage;
  1213.         docText = ((DocumentPeek)currPort)->docTE;
  1214.         textRect = (**docText).viewRect;
  1215.         destRect = (**destRgn).rgnBBox;
  1216.  
  1217.         /* Get the amount that the TextEdit record is scrolled */
  1218.         horzOffset = textRect.left - (**docText).destRect.left;
  1219.         vertOffset = textRect.top - (**docText).destRect.top;
  1220.  
  1221.         /* Source rect is dest rect scrolled, clipped to viewRect and off-screen port */
  1222.         clippedSourceRect = destRect;
  1223.         SectRect( &clippedSourceRect, &textRect, /*<*/&clippedSourceRect );
  1224.         OffsetRect( /*◊*/&clippedSourceRect, horzOffset, vertOffset );
  1225.         SectRect( &clippedSourceRect, &backImage->portRect, /*<*/&clippedSourceRect );
  1226.  
  1227.         /* Dest rect is clipped to viewRect and same size and source rect */
  1228.         clippedDestRect = destRect;
  1229.         SectRect( &clippedDestRect, &textRect, /*<*/&clippedDestRect );
  1230.         clippedDestRect.right = clippedDestRect.left + (clippedSourceRect.right -
  1231.                 clippedSourceRect.left);
  1232.         clippedDestRect.bottom = clippedDestRect.top + (clippedSourceRect.bottom -
  1233.                 clippedSourceRect.top);
  1234.  
  1235.         /* Draw the background instead of erasing */
  1236.         CopyBits( &((GrafPtr)backImage)->portBits, &currPort->portBits,
  1237.                 &clippedSourceRect, &clippedDestRect,
  1238.                 srcCopy, destRgn );
  1239.     }
  1240.     else
  1241.         StdRgn( verb, destRgn );
  1242. }
  1243.  
  1244.  
  1245. /* Create a new document and window. */
  1246.  
  1247. #pragma segment Main
  1248. void DoNew()
  1249. {
  1250.     Boolean        good;
  1251.     Ptr            storage;
  1252.     WindowPtr    window;
  1253.     Rect        destRect, viewRect;
  1254.     DocumentPeek doc;
  1255.     CGrafPtr    savedPort;
  1256.     GDHandle    savedDevice;
  1257.     QDErr       error;
  1258.     QDProcsPtr  customProcs;
  1259.  
  1260.     storage = NewPtr(sizeof(DocumentRecord));
  1261.     if ( storage != nil ) {
  1262.         window = GetNewWindow(rDocWindow, storage, (WindowPtr) -1);
  1263.         if ( window != nil ) {
  1264.             gNumDocuments += 1;            /* this will be decremented when we call DoCloseWindow */
  1265.             good = false;
  1266.             SetPort(window);
  1267.             doc =  (DocumentPeek) window;
  1268.  
  1269.             GetTERect(window, &viewRect);
  1270.             destRect = viewRect;
  1271.             destRect.right = destRect.left + kMaxDocWidth;
  1272.             doc->docTE = TENew(&destRect, &viewRect);
  1273.             good = doc->docTE != nil;    /* if TENew succeeded, we have a good document */
  1274.             if ( good ) {                /* 1.02 - good document? — proceed */
  1275.                 AdjustViewRect(doc->docTE);
  1276.                 TEAutoView(true, doc->docTE);
  1277.                 doc->docClick = (ProcPtr) (*doc->docTE)->clickLoop;
  1278.                 #if powerc
  1279.                 TESetClickLoop(gClickLoopUPP, doc->docTE);
  1280.                 #else
  1281.                 (*doc->docTE)->clickLoop = (TEClickLoopUPP) AsmClickLoopProc;
  1282.                 #endif
  1283.             }
  1284.  
  1285.             /* Create the GWorld to use as the background image */
  1286.             GetGWorld( &savedPort, &savedDevice );
  1287.             error = NewGWorld( &doc->docImage, 0, &window->portRect, nil, nil, 0 );
  1288.             good = error == noErr;
  1289.             if (good)
  1290.             {
  1291.                 /* Draw the image of ramps into the GWorld */
  1292.                 SetGWorld( doc->docImage, nil );
  1293.                 PaintImage();
  1294.                 SetGWorld( savedPort, savedDevice );
  1295.  
  1296.                 /* Allocate and initialize bottleneck routines */
  1297.                 customProcs = (QDProcsPtr)NewPtr( sizeof (QDProcs) );
  1298.                 SetStdProcs(customProcs );
  1299.                 customProcs->rectProc = gQDRectUPP;
  1300.                 customProcs->rgnProc = gQDRgnUPP;
  1301.                 
  1302.                 /* Install our bottlenecks into the window */
  1303.                 window->grafProcs = customProcs;
  1304.             }
  1305.  
  1306.             if ( good ) {                /* good document? — get scrollbars */
  1307.                 doc->docVScroll = GetNewControl(rVScroll, window);
  1308.                 good = (doc->docVScroll != nil);
  1309.             }
  1310.             if ( good) {
  1311.                 doc->docHScroll = GetNewControl(rHScroll, window);
  1312.                 good = (doc->docHScroll != nil);
  1313.             }
  1314.             
  1315.             if ( good ) {                /* good? — adjust & draw the controls, draw the window */
  1316.                 /* false to AdjustScrollValues means musn’t redraw; technically, of course,
  1317.                 the window is hidden so it wouldn’t matter whether we called ShowControl or not. */
  1318.                 AdjustScrollValues(window, false);
  1319.                 ShowWindow(window);
  1320.             } else {
  1321.                 DoCloseWindow(window);    /* otherwise regret we ever created it... */
  1322.                 AlertUser(eNoWindow);            /* and tell user */
  1323.             }
  1324.         } else
  1325.             DisposPtr(storage);            /* get rid of the storage if it is never used */
  1326.     }
  1327. } /*DoNew*/
  1328.  
  1329.  
  1330. /* Close a window. This handles desk accessory and application windows. */
  1331.  
  1332. /*    1.01 - At this point, if there was a document associated with a
  1333.     window, you could do any document saving processing if it is 'dirty'.
  1334.     DoCloseWindow would return true if the window actually closed, i.e.,
  1335.     the user didn’t cancel from a save dialog. This result is handy when
  1336.     the user quits an application, but then cancels the save of a document
  1337.     associated with a window. */
  1338.  
  1339. #pragma segment Main
  1340. Boolean DoCloseWindow(window)
  1341.     WindowPtr    window;
  1342. {
  1343.     TEHandle    te;
  1344.  
  1345.     if ( IsDAWindow(window) )
  1346.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  1347.     else if ( IsAppWindow(window) ) {
  1348.         te = ((DocumentPeek) window)->docTE;
  1349.         if ( te != nil )
  1350.             TEDispose(te);            /* dispose the TEHandle if we got far enough to make one */
  1351.         /*    1.01 - We used to call DisposeWindow, but that was technically
  1352.             incorrect, even though we allocated storage for the window on
  1353.             the heap. We should instead call CloseWindow to have the structures
  1354.             taken care of and then dispose of the storage ourselves. */
  1355.         CloseWindow(window);
  1356.         DisposPtr((Ptr) window);
  1357.         gNumDocuments -= 1;
  1358.     }
  1359.     return true;
  1360. } /*DoCloseWindow*/
  1361.  
  1362.  
  1363. /**************************************************************************************
  1364. *** 1.01 DoCloseBehind(window) was removed ***
  1365.  
  1366.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  1367.     and not having to worry about updating the windows, but it suffered
  1368.     from a fatal flaw. If a desk accessory owned two windows, it would
  1369.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  1370.     got around to calling DoCloseWindow for that other window that was already
  1371.     closed, things would go very poorly. Another option would be to have a
  1372.     procedure, GetRearWindow, that would go through the window list and return
  1373.     the last window. Instead, we decided to present the standard approach
  1374.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  1375.     has a potential benefit in that the window whose document needs to be saved
  1376.     may be visible since it is the front window, therefore decreasing the
  1377.     chance of user confusion. For aesthetic reasons, the windows in the
  1378.     application should be checked for updates periodically and have the
  1379.     updates serviced.
  1380. **************************************************************************************/
  1381.  
  1382.  
  1383. /* Clean up the application and exit. We close all of the windows so that
  1384.  they can update their documents, if any. */
  1385.  
  1386. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  1387.     shell, but will return instead. */
  1388.  
  1389. #pragma segment Main
  1390. void Terminate()
  1391. {
  1392.     WindowPtr    aWindow;
  1393.     Boolean        closed;
  1394.     
  1395.     closed = true;
  1396.     do {
  1397.         aWindow = FrontWindow();                /* get the current front window */
  1398.         if (aWindow != nil)
  1399.             closed = DoCloseWindow(aWindow);    /* close this window */    
  1400.     }
  1401.     while (closed && (aWindow != nil));
  1402.     if (closed)
  1403.         ExitToShell();                            /* exit if no cancellation */
  1404. } /*Terminate*/
  1405.  
  1406.  
  1407. /*    Set up the whole world, including global variables, Toolbox managers,
  1408.     menus, and a single blank document. */
  1409.  
  1410. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  1411.     this module. If an error is detected, instead of merely doing an ExitToShell,
  1412.     which leaves the user without much to go on, we call AlertUser, which puts
  1413.     up a simple alert that just says an error occurred and then calls ExitToShell.
  1414.     Since there is no other cleanup needed at this point if an error is detected,
  1415.     this form of error- handling is acceptable. If more sophisticated error recovery
  1416.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  1417.     
  1418.  
  1419. #pragma segment Initialize
  1420. void Initialize()
  1421. {
  1422.     Handle    menuBar;
  1423.     long    total, contig;
  1424.     EventRecord event;
  1425.     short    count;
  1426.  
  1427.     gInBackground = false;
  1428.  
  1429.     InitGraf((Ptr) &qd.thePort);
  1430.     InitFonts();
  1431.     InitWindows();
  1432.     InitMenus();
  1433.     TEInit();
  1434.     InitDialogs(nil);
  1435.     InitCursor();
  1436.  
  1437.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  1438.          if you are using it. */
  1439.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  1440.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  1441.         of checking for port availability themselves. */
  1442.     
  1443.     /*    This next bit of code is necessary to allow the default button of our
  1444.         alert be outlined.
  1445.         1.02 - Changed to call EventAvail so that we don't lose some important
  1446.         events. */
  1447.      
  1448.     for (count = 1; count <= 3; count++)
  1449.         EventAvail(everyEvent, &event);
  1450.     
  1451.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  1452.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  1453.         call to SysEnvirons by calling it after initializing AppleTalk. */
  1454.      
  1455.     SysEnvirons(kSysEnvironsVersion, &gMac);
  1456.     
  1457.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  1458.     
  1459.     if (gMac.machineType < 0) BigBadError(eWrongMachine);
  1460.     
  1461.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  1462.         in TrapAvailable if a tool trap value is out of range. */
  1463.         
  1464.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent);
  1465.  
  1466.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  1467.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  1468.         MultiFinder we needed. This did not work well because it assumed too much about
  1469.         the relationship between what we asked MultiFinder for and what we would actually
  1470.         get back, as well as how to measure it. Instead, we will use an alternate
  1471.         method comprised of two steps. */
  1472.      
  1473.     /*    It is better to first check the size of the application heap against a value
  1474.         that you have determined is the smallest heap the application can reasonably
  1475.         work in. This number should be derived by examining the size of the heap that
  1476.         is actually provided by MultiFinder when the minimum size requested is used.
  1477.         The derivation of the minimum size requested from MultiFinder is described
  1478.         in Sample.h. The check should be made because the preferred size can end up
  1479.         being set smaller than the minimum size by the user. This extra check acts to
  1480.         insure that your application is starting from a solid memory foundation. */
  1481.      
  1482.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) BigBadError(eSmallSize);
  1483.     
  1484.     /*    Next, make sure that enough memory is free for your application to run. It
  1485.         is possible for a situation to arise where the heap may have been of required
  1486.         size, but a large scrap was loaded which left too little memory. To check for
  1487.         this, call PurgeSpace and compare the result with a value that you have determined
  1488.         is the minimum amount of free memory your application needs at initialization.
  1489.         This number can be derived several different ways. One way that is fairly
  1490.         straightforward is to run the application in the minimum size configuration
  1491.         as described previously. Call PurgeSpace at initialization and examine the value
  1492.         returned. However, you should make sure that this result is not being modified
  1493.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  1494.         PurgeSpace. Make sure to remove that call before shipping, though. */
  1495.     
  1496.     /* ZeroScrap(); */
  1497.  
  1498.     PurgeSpace(&total, &contig);
  1499.     if (total < kMinSpace)
  1500.         if (UnloadScrap() != noErr)
  1501.             BigBadError(eNoMemory);
  1502.         else {
  1503.             PurgeSpace(&total, &contig);
  1504.             if (total < kMinSpace)
  1505.                 BigBadError(eNoMemory);
  1506.         }
  1507.  
  1508.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  1509.         to check memory is that we can now give the user an alert to tell him/her what
  1510.         happened. Although it is possible that the memory situation could be worsened by
  1511.         displaying an alert, MultiFinder would gracefully exit the application with
  1512.         an informative alert if memory became critical. Here we are acting more
  1513.         in a preventative manner to avoid future disaster from low-memory problems. */
  1514.  
  1515.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  1516.     if ( menuBar == nil )
  1517.                 BigBadError(eNoMemory);
  1518.     SetMenuBar(menuBar);                    /* install menus */
  1519.     DisposHandle(menuBar);
  1520.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  1521.     DrawMenuBar();
  1522.  
  1523.     gNumDocuments = 0;
  1524.     
  1525.     /* set up the UPP for our ClikLoop if we are compiling for PowerPC */
  1526.     #if powerc
  1527.     gClickLoopUPP = NewTEClickLoopProc(ClickLoopProc);
  1528.     #endif
  1529.     
  1530.     /* set up the UPPs for our scroll bar tracking */
  1531.     gHActionUPP = NewControlActionProc(HActionProc);
  1532.     gVActionUPP = NewControlActionProc(VActionProc);
  1533.     
  1534.     /* finally the UPPs for the QD routines */
  1535.     gQDRectUPP   =  NewQDRectProc(CustomRect);
  1536.     gQDRgnUPP    =  NewQDRgnProc(CustomRgn);
  1537.  
  1538.     /* do other initialization here */
  1539.  
  1540.     DoNew();                                /* create a single empty document */
  1541. } /*Initialize*/
  1542.  
  1543.  
  1544. /* Used whenever a, like, fully fatal error happens */
  1545. #pragma segment Initialize
  1546. void BigBadError(error)
  1547.     short error;
  1548. {
  1549.     AlertUser(error);
  1550.     ExitToShell();
  1551. }
  1552.  
  1553.  
  1554. /* Return a rectangle that is inset from the portRect by the size of
  1555.     the scrollbars and a little extra margin. */
  1556.  
  1557. #pragma segment Main
  1558. void GetTERect(window,teRect)
  1559.     WindowPtr    window;
  1560.     Rect        *teRect;
  1561. {
  1562.     *teRect = window->portRect;
  1563.     InsetRect(teRect, kTextMargin, kTextMargin);    /* adjust for margin */
  1564.     teRect->bottom = teRect->bottom - 15;        /* and for the scrollbars */
  1565.     teRect->right = teRect->right - 15;
  1566. } /*GetTERect*/
  1567.  
  1568.  
  1569. /* Update the TERec's view rect so that it is the greatest multiple of
  1570.     the lineHeight that still fits in the old viewRect. */
  1571.  
  1572. #pragma segment Main
  1573. void AdjustViewRect(docTE)
  1574.     TEHandle    docTE;
  1575. {
  1576.     TEPtr        te;
  1577.     
  1578.     te = *docTE;
  1579.     /* te->viewRect.bottom = (((te->viewRect.bottom - te->viewRect.top) / te->lineHeight)
  1580.                             * te->lineHeight) + te->viewRect.top; */
  1581. } /*AdjustViewRect*/
  1582.  
  1583.  
  1584. /* Scroll the TERec around to match up to the potentially updated scrollbar
  1585.     values. This is really useful when the window has been resized such that the
  1586.     scrollbars became inactive but the TERec was already scrolled. */
  1587.  
  1588. #pragma segment Main
  1589. void AdjustTE(window)
  1590.     WindowPtr    window;
  1591. {
  1592.     TEPtr        te;
  1593.     
  1594.     te = *((DocumentPeek)window)->docTE;
  1595.     TEScroll((te->viewRect.left - te->destRect.left) -
  1596.             GetCtlValue(((DocumentPeek)window)->docHScroll),
  1597.             (te->viewRect.top - te->destRect.top) -
  1598.                 (GetCtlValue(((DocumentPeek)window)->docVScroll) *
  1599.                 te->lineHeight),
  1600.             ((DocumentPeek)window)->docTE);
  1601. } /*AdjustTE*/
  1602.  
  1603.  
  1604. /* Calculate the new control maximum value and current value, whether it is the horizontal or
  1605.     vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  1606.     vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  1607.     width to the width of the viewRect. The current values are set by comparing the offset between
  1608.     the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  1609.     calling ShowControl. */
  1610.  
  1611. #pragma segment Main
  1612. void AdjustHV(isVert,control,docTE,canRedraw)
  1613.     Boolean        isVert;
  1614.     ControlHandle control;
  1615.     TEHandle    docTE;
  1616.     Boolean        canRedraw;
  1617. {
  1618.     short        value, lines, max;
  1619.     short        oldValue, oldMax;
  1620.     TEPtr        te;
  1621.     
  1622.     oldValue = GetCtlValue(control);
  1623.     oldMax = GetCtlMax(control);
  1624.     te = *docTE;                            /* point to TERec for convenience */
  1625.     if ( isVert ) {
  1626.         lines = te->nLines;
  1627.         /* since nLines isn’t right if the last character is a return, check for that case */
  1628.         if ( *(*te->hText + te->teLength - 1) == kCrChar )
  1629.             lines += 1;
  1630.         max = lines - ((te->viewRect.bottom - te->viewRect.top) /
  1631.                 te->lineHeight);
  1632.     } else
  1633.         max = kMaxDocWidth - (te->viewRect.right - te->viewRect.left);
  1634.     
  1635.     if ( max < 0 ) max = 0;
  1636.     SetCtlMax(control, max);
  1637.     
  1638.     /* Must deref. after SetCtlMax since, technically, it could draw and therefore move
  1639.         memory. This is why we don’t just do it once at the beginning. */
  1640.     te = *docTE;
  1641.     if ( isVert )
  1642.         value = (te->viewRect.top - te->destRect.top) / te->lineHeight;
  1643.     else
  1644.         value = te->viewRect.left - te->destRect.left;
  1645.     
  1646.     if ( value < 0 ) value = 0;
  1647.     else if ( value >  max ) value = max;
  1648.     
  1649.     SetCtlValue(control, value);
  1650.     /* now redraw the control if it needs to be and can be */
  1651.     if ( canRedraw || (max != oldMax) || (value != oldValue) )
  1652.         ShowControl(control);
  1653. } /*AdjustHV*/
  1654.  
  1655.  
  1656. /* Simply call the common adjust routine for the vertical and horizontal scrollbars. */
  1657.  
  1658. #pragma segment Main
  1659. void AdjustScrollValues(window,canRedraw)
  1660.     WindowPtr    window;
  1661.     Boolean        canRedraw;
  1662. {
  1663.     DocumentPeek doc;
  1664.     
  1665.     doc = (DocumentPeek)window;
  1666.     AdjustHV(true, doc->docVScroll, doc->docTE, canRedraw);
  1667.     AdjustHV(false, doc->docHScroll, doc->docTE, canRedraw);
  1668. } /*AdjustScrollValues*/
  1669.  
  1670.  
  1671. /*    Re-calculate the position and size of the viewRect and the scrollbars.
  1672.     kScrollTweek compensates for off-by-one requirements of the scrollbars
  1673.     to have borders coincide with the growbox. */
  1674.  
  1675. #pragma segment Main
  1676. void AdjustScrollSizes(window)
  1677.     WindowPtr    window;
  1678. {
  1679.     Rect        teRect;
  1680.     DocumentPeek doc;
  1681.     
  1682.     doc = (DocumentPeek) window;
  1683.     GetTERect(window, &teRect);                            /* start with TERect */
  1684.     (*doc->docTE)->viewRect = teRect;
  1685.     AdjustViewRect(doc->docTE);                            /* snap to nearest line */
  1686.     MoveControl(doc->docVScroll, window->portRect.right - kScrollbarAdjust, -1);
  1687.     SizeControl(doc->docVScroll, kScrollbarWidth, (window->portRect.bottom - 
  1688.                 window->portRect.top) - (kScrollbarAdjust - kScrollTweek));
  1689.     MoveControl(doc->docHScroll, -1, window->portRect.bottom - kScrollbarAdjust);
  1690.     SizeControl(doc->docHScroll, (window->portRect.right - 
  1691.                 window->portRect.left) - (kScrollbarAdjust - kScrollTweek),
  1692.                 kScrollbarWidth);
  1693. } /*AdjustScrollSizes*/
  1694.  
  1695.  
  1696. /* Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  1697.     and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  1698.     then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  1699.     by jamming a $FF in their contrlVis fields. */
  1700.  
  1701. #pragma segment Main
  1702. void AdjustScrollbars(window,needsResize)
  1703.     WindowPtr    window;
  1704.     Boolean        needsResize;
  1705. {
  1706.     DocumentPeek doc;
  1707.     
  1708.     doc = (DocumentPeek) window;
  1709.     /* First, turn visibility of scrollbars off so we won’t get unwanted redrawing */
  1710.     (*doc->docVScroll)->contrlVis = kControlInvisible;    /* turn them off */
  1711.     (*doc->docHScroll)->contrlVis = kControlInvisible;
  1712.     if ( needsResize )                                    /* move & size as needed */
  1713.         AdjustScrollSizes(window);
  1714.     AdjustScrollValues(window, needsResize);            /* fool with max and current value */
  1715.     /* Now, restore visibility in case we never had to ShowControl during adjustment */
  1716.     (*doc->docVScroll)->contrlVis = kControlVisible;    /* turn them on */
  1717.     (*doc->docHScroll)->contrlVis = kControlVisible;
  1718. } /* AdjustScrollbars */
  1719.  
  1720.  
  1721. // When the user selects text by dragging, TextEdit repeatedly calls a click loop routine which
  1722. // it gets from the TERecord's clikLoop field. TextEdit's default routine does some useful things,
  1723. // such as scrolling the text being selected, but it doesn't know about our scroll bars.
  1724. // Therefore, we replace the routine with one that calls both the old routine and an add-on routine
  1725. // which handles the scroll bars. Unfortunately, the way this works is very different for 68K and
  1726. // PowerPC. On 68K, we have to be aware that the original click loop routine has a register-based
  1727. // interface, so our replacement is easier to write in assembly. For PowerPC, we can let routine
  1728. // descriptors handle the argument conversions, and do everything in the C routine ClickLoopProc.
  1729.  
  1730. #if powerc
  1731. pascal Boolean ClickLoopProc(TEPtr pTE)
  1732. {
  1733.     CallTEClickLoopProc(GetOldClickLoop(), pTE);
  1734.     ClickLoopAddOn();
  1735.     return true;
  1736. }
  1737. #endif
  1738.  
  1739.  
  1740. // The ClickLoopAddOn routine handles the scroll bars during drag-scrolling.
  1741.  
  1742. pascal void ClickLoopAddOn(void)
  1743. {
  1744.     WindowPtr    window;
  1745.     RgnHandle    region;
  1746.     
  1747.     window = FrontWindow();
  1748.     region = NewRgn();
  1749.     GetClip(region);                    /* save clip */
  1750.     ClipRect(&window->portRect);
  1751.     AdjustScrollValues(window, true);    /* pass true for canRedraw */
  1752.     SetClip(region);                    /* restore clip */
  1753.     DisposeRgn(region);
  1754. }
  1755.  
  1756.  
  1757. // GetOldClickLoop returns the address of the default click loop routine that we put into the
  1758. // TERec when creating it.
  1759.  
  1760. pascal TEClickLoopUPP GetOldClickLoop(void)
  1761. {
  1762.     return ((DocumentPeek)FrontWindow())->docClick;
  1763. }
  1764.  
  1765.  
  1766. /*    Check to see if a window belongs to the application. If the window pointer
  1767.     passed was NIL, then it could not be an application window. WindowKinds
  1768.     that are negative belong to the system and windowKinds less than userKind
  1769.     are reserved by Apple except for windowKinds equal to dialogKind, which
  1770.     mean it is a dialog.
  1771.     1.02 - In order to reduce the chance of accidentally treating some window
  1772.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  1773.     is userKind. If you add different kinds of windows to Sample you'll need
  1774.     to change how this all works. */
  1775.  
  1776. #pragma segment Main
  1777. Boolean IsAppWindow(window)
  1778.     WindowPtr    window;
  1779. {
  1780.     short        windowKind;
  1781.  
  1782.     if ( window == nil )
  1783.         return false;
  1784.     else {    /* application windows have windowKinds = userKind (8) */
  1785.         windowKind = ((WindowPeek) window)->windowKind;
  1786.         return (windowKind == userKind);
  1787.     }
  1788. } /*IsAppWindow*/
  1789.  
  1790.  
  1791. /* Check to see if a window belongs to a desk accessory. */
  1792.  
  1793. #pragma segment Main
  1794. Boolean IsDAWindow(window)
  1795.     WindowPtr    window;
  1796. {
  1797.     if ( window == nil )
  1798.         return false;
  1799.     else    /* DA windows have negative windowKinds */
  1800.         return ((WindowPeek) window)->windowKind < 0;
  1801. } /*IsDAWindow*/
  1802.  
  1803.  
  1804. // check to see if a given trap is implemented. We follow IM VI-3-8.
  1805.  
  1806. Boolean TrapAvailable(short theTrap)
  1807. {
  1808.     TrapType theTrapType;
  1809.     short numToolboxTraps;
  1810.     
  1811.     if ((theTrap & 0x0800) > 0)
  1812.         theTrapType = ToolTrap;
  1813.     else
  1814.         theTrapType = OSTrap;
  1815.  
  1816.     if (theTrapType == ToolTrap)
  1817.     {
  1818.         theTrap = theTrap & 0x07ff;
  1819.         if (NGetTrapAddress(_InitGraf, ToolTrap) == NGetTrapAddress(0xaa6e, ToolTrap))
  1820.             numToolboxTraps = 0x0200;
  1821.         else
  1822.             numToolboxTraps = 0x0400;
  1823.         if (theTrap >= numToolboxTraps)
  1824.             theTrap = _Unimplemented;
  1825.     };
  1826.  
  1827.     return (NGetTrapAddress(theTrap, theTrapType) != NGetTrapAddress(_Unimplemented, ToolTrap));
  1828. }
  1829.  
  1830.  
  1831. /*    Display an alert that tells the user an error occurred, then exit the program.
  1832.     This routine is used as an ultimate bail-out for serious errors that prohibit
  1833.     the continuation of the application. Errors that do not require the termination
  1834.     of the application should be handled in a different manner. Error checking and
  1835.     reporting has a place even in the simplest application. The error number is used
  1836.     to index an 'STR#' resource so that a relevant message can be displayed. */
  1837.  
  1838. #pragma segment Main
  1839. void AlertUser(error)
  1840.     short        error;
  1841. {
  1842.     short        itemHit;
  1843.     Str255        message;
  1844.  
  1845.     SetCursor(&qd.arrow);
  1846.     /* type Str255 is an array in MPW 3 */
  1847.     GetIndString(message, kErrStrings, error);
  1848.     ParamText(message, "", "", "");
  1849.     itemHit = Alert(rUserAlert, nil);
  1850. } /* AlertUser */
  1851.